package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VisitorsApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.MovementsVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VisitorsVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.utils.Constants;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class MovementService {
    @Autowired
    private OssTemplate ossTemplate;

    @DubboReference
    private MovementApi movementApi;
    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @DubboReference
    private VisitorsApi visitorsApi;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private  MqMessageService mqMessageService;

    public void publishMovement(Movement movement, MultipartFile[] imageContent) throws IOException {
        if (StringUtils.isEmpty(movement.getTextContent())) {
            throw new BusinessException(ErrorResult.contentError());
        }
        List<String> list = new ArrayList<>();
        for (MultipartFile multipartFile : imageContent) {
            String upload = ossTemplate.upload(multipartFile.getOriginalFilename(), multipartFile.getInputStream());
            list.add(upload);
        }
        Long userId = UserHolder.getUserId();
        movement.setUserId(userId);
        movement.setMedias(list);

       String movementid = movementApi.publish(movement);
        mqMessageService.sendAudiMessage(movementid);
        mqMessageService.sendLogMessage(UserHolder.getUserId(),"0201","movement",movementid);

    }

    public PageResult findByUserId(Long userId, Integer page, Integer pagesize) {
        PageResult pr = movementApi.findByUserId(userId, page, pagesize);
        List<Movement> items = (List<Movement>) pr.getItems();
        if (items == null) {
            return pr;
        }
        UserInfo userInfo = userInfoApi.findById(userId);
        List<MovementsVo> list = new ArrayList<>();
        for (Movement item : items) {
            MovementsVo movementsVo = MovementsVo.init(userInfo, item);
            list.add(movementsVo);
        }
        pr.setItems(list);
        return pr;
    }

    public PageResult findFriendMovements(Integer page, Integer pagesize) {
        Long userId = UserHolder.getUserId();
        List<Movement> list = movementApi.movements(page, pagesize, userId);
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        List<Long> userids = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findbyIds(userids, null);
        List<MovementsVo> movementsVoList = new ArrayList<>();
        for (Movement movement : list) {
            UserInfo userInfo = map.get(movement.getUserId());
            if (userInfo != null) {
                MovementsVo vo = MovementsVo.init(userInfo, movement);
                String key = Constants.MOVEMENTS_INTERACT_KEY + UserHolder.getUserId().toString();
                String hashKey = Constants.USER_LIKE_KEY + UserHolder.getUserId();
                if(redisTemplate.opsForHash().hasKey(key,hashKey)) {
                    vo.setHasLiked(1);
                }
                String lovehashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
                if(redisTemplate.opsForHash().hasKey(key,lovehashKey)) {
                    vo.setHasLoved(1);
                }


                movementsVoList.add(vo);
            }
        }
        return new PageResult(page, pagesize, 0l, movementsVoList);

    }

    public PageResult findFriendrecommend(Integer page, Integer pagesize) {

        String rediscalue = redisTemplate.opsForValue().get(Constants.MOVEMENTS_INTERACT_KEY + UserHolder.getUserId());
        List<Movement> list = new ArrayList<>();
        if (StringUtils.isEmpty(rediscalue)) {
            list = movementApi.randmvements(pagesize);

        } else {
            String[] rediscaluesplit = rediscalue.split(",");
            if ((page - 1) * pagesize < rediscaluesplit.length) {
                List<Long> pids = Arrays.stream(rediscaluesplit).skip((page - 1) * pagesize)
                        .map(a -> Long.valueOf(a)).collect(Collectors.toList());
                list = movementApi.findBypids(pids);
            }
        }
        List<Long> userids = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findbyIds(userids, null);
        List<MovementsVo> movementsVoList = new ArrayList<>();
        for (Movement movement : list) {
            UserInfo userInfo = map.get(movement.getUserId());
            if (userInfo != null) {
                MovementsVo vo = MovementsVo.init(userInfo, movement);
                String key = Constants.MOVEMENTS_INTERACT_KEY + movement.getId().toHexString();
                String hashKey = Constants.PINGLUN_LIKE_HASHKEY + UserHolder.getUserId();
                if (redisTemplate.opsForHash().hasKey(key, hashKey)) {
                    vo.setHasLiked(1);
                }
                String lovehashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
                if(redisTemplate.opsForHash().hasKey(key,lovehashKey)) {
                    vo.setHasLoved(1);
                }

                movementsVoList.add(vo);
            }

        }
        return new PageResult(page, pagesize, 0l, movementsVoList);
    }
    public MovementsVo findById(String movementId) {
        mqMessageService.sendLogMessage(UserHolder.getUserId(),"0202","movement",movementId);
        Movement movement = movementApi.findById(movementId);
        if (movement != null) {
            UserInfo userInfo = userInfoApi.findById(movement.getUserId());
            return MovementsVo.init(userInfo, movement);
        } else {
            return null;
        }
    }

    public List<VisitorsVo> queryVisitorsList() {
        String key = Constants.VISITORS_USER;
        String hashkey = String.valueOf(UserHolder.getUserId());
        String visitorndata = (String) redisTemplate.opsForHash().get(key, hashkey);
        Long data = StringUtils.isEmpty(visitorndata)? null:Long.valueOf(visitorndata);
       List<Visitors> visitorsList = visitorsApi.myvisitorsList(data,UserHolder.getUserId());
       if (CollUtil.isEmpty(visitorsList)){
           return new ArrayList<>();
       }
        List<Long> visitorUserId = CollUtil.getFieldValues(visitorsList, "visitorUserId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findbyIds(visitorUserId, null);
        List<VisitorsVo> visitorsVoList = new ArrayList<>();
        for (Visitors visitors : visitorsList) {
            UserInfo userInfo = map.get(visitors.getVisitorUserId());
            if (userInfo!=null){
                VisitorsVo visitorsVo = VisitorsVo.init(userInfo, visitors);
                visitorsVoList.add(visitorsVo);
            }
        }
        return visitorsVoList;
    }
}
